import Utils from '../../utils'
import Store from '../../store'

export default {
  getUserInfo () {
    return new Promise((resolve, reject) => {
      Utils.Http.$get('/api/security/user').then(userResponse => {
        let user = ''
        let permissions = []
        console.log('get user in user service result => ', JSON.parse(JSON.stringify(userResponse)))
        if (userResponse.data) {
          user = userResponse.data
          permissions = userResponse.data.permissions
        } else {
          Utils.Http.$get('/api/security/info').then(infoResponse => {
            console.log('get info in user service result => ', JSON.parse(JSON.stringify(infoResponse)))
            location.href = infoResponse.data.loginUrl
          })
        }
        sessionStorage.setItem('user', JSON.stringify(user))
        sessionStorage.setItem('permission', permissions.join(','))

        Store.commit('setUser', user)
        Store.commit('setPermission', permissions)
        resolve && resolve()
      })
    })
  },
  async isLogin () {
    const response = await Utils.Http.$get('/api/security/user')
    const isLogin = response.code !== 50003
    if (isLogin) {
      let user = response.data
      let permissions = response.data.permissions

      sessionStorage.setItem('user', JSON.stringify(user))
      sessionStorage.setItem('permission', permissions.join(','))

      Store.commit('setUser', user)
      Store.commit('setPermission', permissions)
    }
    return response.code !== 50003
  },
  async toLogin () {
    const infoResponse = await Utils.Http.$get('/api/security/info')
    console.log('get info in user service result => ', JSON.parse(JSON.stringify(infoResponse)))
    location.href = infoResponse.data.loginUrl
  }
}
